<template>
  <el-card>
    <!-- 搜索头 -->
    <transition name="el-zoom-in-top">
      <el-form v-show="searchShow" :inline="true" label-width="80px">
        <el-form-item label="场景名称">
          <el-input v-model="listQuery.title" size="small"/>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" @click="handleSearchClick">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button size="small" @click="handleSearchCleanClick">清空</el-button>
        </el-form-item>
      </el-form>
    </transition>

    <!-- 工具栏 -->
    <div class="tools-container">
      <div class="buttons">
        <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleBindClick">绑定新设备</el-button>
      </div>
      <div class="tags">
        <el-button size="mini" icon="el-icon-search" circle @click="handleSearchShowChange"/>
        <el-button size="mini" icon="el-icon-refresh" circle @click="handleRefreshClick"/>
        <el-button size="mini" icon="el-icon-menu" circle @click="handleHeaderClick"/>
      </div>
    </div>

    <!-- 表头 -->
    <el-dialog :visible.sync="headerShow" :close-on-click-modal="false" :close-on-press-escape="false" title="表头">
      <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
      <div style="margin: 15px 0;"/>
      <el-checkbox-group v-model="header">
        <el-checkbox v-for="(value, key) in columns" :key="key" :label="key" :prop="key" >{{ value.label }}</el-checkbox>
      </el-checkbox-group>
    </el-dialog>

    <!-- 表格 -->
    <el-table v-loading="listLoading" ref="table" :data="list" size="mini" class="table-container" element-loading-text="加载中..." border fit highlight-current-row @sort-change="handleSortChange">
      <el-table-column type="index" width="50" label="序号"/>
      <el-table-column v-for="(value, key) in columns" v-if="value.show" :key="key" :label="value.label" :prop="key" sortable/>
      <el-table-column  align="center" label="操作" width="200">
        <template slot-scope="scope">
          <el-button v-if="scope.row.type === 0" size="mini" type="text" icon="el-icon-sort" @click="handleBindClick1">替换</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleUnBindClick(scope.row)">解绑</el-button>
          <el-button size="mini" type="text" icon="el-icon-location" @click="handlePositionClick(scope.row)">坐标</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 绑定设备 -->
    <el-dialog :visible.sync="bindShow" :close-on-click-modal="false" :close-on-press-escape="false" :before-close="handleBeforeClose" title="绑定设备">
      <unbound-device :scene="listQuery.scene" @refreshP="resh"/>
    </el-dialog>

    <!--替换设备-->
    <el-dialog :visible.sync="bindShow1" :close-on-click-modal="false" :close-on-press-escape="false" :before-close="handleBeforeClose" title="绑定设备">
      <replace :scene="listQuery.scene" @refreshP="resh"/>
    </el-dialog>
    <!-- 表单2 -->
    <amap-position2 v-if="positionShow" :width="windowWidth" :edit-show.sync="positionShow" :scene="listQuery.scene" :id="row.id" :line="{lng: row.lng, lat: row.lat, type: row.type}"/>

    <!-- 分页 组件 -->
    <el-pagination :current-page.sync="listQuery.page" :page-size="listQuery.size" :total="total" :page-sizes="[5,10,20,30,50]" class="pagination-container" background layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
  </el-card>
</template>

<script>

import { columns } from '@/api/device'
import { sceneDevicePage, unbindDevice } from '@/api/scene'
import { toLowerCase } from '@/utils'
import UnboundDevice from './unboundDevice'
import Replace from './replace'
import amapPosition2 from './amapPosition2'
import { check } from '@/utils/check'
import { mapGetters } from 'vuex'

export default {
  components: {
    UnboundDevice,
    amapPosition2,
    Replace
  },
  props: {
    scene: {
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      listQuery: {
        page: 1,
        size: 5,
        order: 'id',
        scene: this.scene,
        title: '',
        type: 2, // 0： 查询中控， 1： 查询点位
        bind: true // 绑定的设备
      },
      total: 0,
      searchShow: false,
      bindShow: false,
      bindShow1: false,
      positionShow: false,
      headerShow: false,
      isIndeterminate: true,
      checkAll: true,
      columns: [],
      row: {},
      checkBind: false,
      checkUnbind: false,
      windowWidth: 0
    }
  },
  computed: {
    // ...mapGetters([
    //   'roles'
    // ]),
    header: {
      set: function(v) {
        Object.keys(this.columns).forEach(key => {
          this.columns[key].show = false
          v.forEach(i => {
            if (key === i) {
              this.columns[key].show = true
            }
          })
        })
        const checkedCount = v.length
        this.checkAll = checkedCount === Object.keys(this.columns).length
        console.log(this.checkAll)
        this.isIndeterminate = checkedCount > 0 && checkedCount < Object.keys(this.columns).length
        console.log(this.isIndeterminate, v.length, Object.keys(this.columns).length)
        return Object.keys(this.columns).filter(i => this.columns[i].show)
      },
      get: function() {
        var array = Object.keys(this.columns).filter(i => this.columns[i].show)
        return array
      }
    }
  },
  mounted() {
    this.windowWidth = window.innerWidth / 2 - 60
    // check(this.roles, ['绑定设备', '解绑设备', '添加测量组设备'], (list) => {
    //   this.checkBind = list[0]
    //   this.checkUnbind = list[0]
    // })
    this.fetchData()
    this.columns = columns()
    var checkedCount = this.header.length
    this.checkAll = checkedCount === Object.keys(this.columns).length
    this.isIndeterminate = checkedCount > 0 && checkedCount < Object.keys(this.columns).length
  },
  methods: {
    resh(bool) {
      if (bool) {
        this.fetchData()
      }
    },
    fetchData() {
      this.listLoading = true
      sceneDevicePage(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },

    // <<<< 搜索头
    handleSearchClick() {
      if (!this.listQuery.title) {
        this.$message({
          message: '搜索内容不能为空',
          type: 'error',
          duration: 800
        })
      }
    },
    handleSearchCleanClick() {
      this.listQuery.title = ''
    },
    // >>>> 搜索头

    // <<<< 工具栏相关
    handleCheckAllChange(val) {
      this.header = val ? Object.keys(this.columns) : []
      Object.keys(this.columns).forEach(key => {
        this.columns[key].show = val
      })
      this.isIndeterminate = false
    },
    handleRefreshClick() {
      this.$message({
        message: '刷新成功',
        type: 'success',
        duration: 800
      })
      this.fetchData()
    },
    handleSearchShowChange() {
      this.searchShow = !this.searchShow
    },
    handleBindClick() {
      this.bindShow = true
      this.row = {}
    },
    handleBindClick1() {
      this.bindShow1 = true
      this.row = {}
    },
    // >>>> 工具栏相关

    // <<<< 表头相关

    // >>>> 表头相关

    // <<<< 表格相关
    handleUnBindClick(row) {
      this.$confirm('此操作将解绑该设备, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          unbindDevice({deviceId: row.id}).then(res => {
            if (res.ok) {
              this.$message({
                message: res.data,
                type: 'success',
                duration: 800
              })
              this.fetchData()
            } else {
              this.$message({
                message: res.data,
                type: 'success',
                duration: 800
              })
            }
          })
        })
        .catch(() => {
          console.log('取消解绑')
        })
    },
    handlePositionClick(row) {
      this.positionShow = true
      this.row = row
    },
    handleBeforeClose(done) {
      this.bindShow = false
      this.positionShow = false
      done()
    },
    // >>>> 表格相关

    // <<<< 分页相关
    handleSizeChange(val) {
      console.log(val)
      this.listQuery.size = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.fetchData()
    },
    handleSortChange(val) {
      this.listQuery.asc = val.order !== 'descending'
      this.listQuery.order = toLowerCase(val.prop)
      this.fetchData()
    },
    handleHeaderClick() {
      this.headerShow = true
    }
    // >>>> 分页相关

    // <<<<< 其他业务
    // >>>>> 其他业务
  }
}
</script>
